package thread;

import java.util.WeakHashMap;

/**
 * 桌上豆子，两个线程都在拿走，因时间片不固定，所以，1~0时会直接跳过判断，进入到负数，并发的缺陷：概率事件
 */
public class SyncDemo { //同步演示
    public static void main(String[] args) {
    Table table = new Table();

         Thread t1=new Thread(){
             public void run(){
                 while (true){
                     int bean = table.getBean();
                     Thread.yield();
                     System.out.println(getName()+":"+bean);
                 }
             }

        };
         Thread t2=new Thread(){
             public void run(){
                 while (true){
                     int bean = table.getBean();
                     Thread.yield();
                     System.out.println(getName()+":"+bean);
                 }
             }

        };

        t1.start();
        t2.start();

    }

}
class  Table{
    private  int beans = 20;

    public synchronized int getBean(){
        if(beans == 0){
            throw new RuntimeException("没有豆子了");
        }
        Thread.yield();
        return beans--;
    }
}